<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 *  Films Controller
 *
 * @package XGO CMS v2.0
 * @subpackage Films
 * @author Manh Nguyen - 30/07/2012
 * @link http://sunsoft.vn
 */
class Films extends CI_Controller {
    /**
     * Contrust class
     *
     * @access public
     */
    public function __construct() {
        parent::__construct();

		$this->load->library('smarty3', '', 'smarty');
        
        require_once(APPPATH . 'modules/backend/autoload.php');        
        
        $this->load->library('login_manager');
        require_once(APPPATH . 'modules/backend/info.php');
        
        $this->load->helper('formatdate');

        $this->login_manager->check_role('films');
        $this->load->language('backend');
        
        //$this->lang->load('backend','vietnamese');
        $this->smarty->assign('language', $this->lang);
        $this->smarty->assign('message', $this->session->flashdata('message'));
        $this->smarty->assign('error_message', $this->session->flashdata('error_message'));
        require_once(APPPATH . 'modules/backend/kcfinder.php');
    }

    /**
     * index function, show jquery grid
     *
     * @access public
     * @param null
     * @return void
     */
    function index() {    
        $parameters = $this->uri->ruri_to_assoc();

        if (isset($parameters['id'])) {
            $id = intval($parameters['id']);
            if ($id > 0) {
                $this->session->set_userdata('search_id', $id);
            }
        }

        $css_files = array(base_url() . 'data/jscripts/jqgrid/css/ui.jqgrid.css');

        $js_files = array(
            base_url() . 'data/jscripts/jqgrid/i18n/grid.locale-vi.js',
            base_url() . 'data/jscripts/jqgrid/jquery.jqGrid.min.js'
        );

        require_once(APPPATH . 'modules/backend/history.php');
        $films = new Films_model();

        //load parameters and initialize grid
        $jqgrid = array();

        $jqgrid['id'] = 'jqgrid';
        $jqgrid['pager'] = 'pagered';
        $jqgrid['caption'] = $films->localize_label('manager');
        $jqgrid['url_metadata'] = site_url($this->router->directory . 'films/jqgrid_jsoninit');
        $jqgrid['url_data'] = site_url($this->router->directory . 'films/jqgrid_jsondata');
        $jqgrid['url_create'] = site_url($this->router->directory . 'films/create');
        $jqgrid['url_edit'] = site_url($this->router->directory . 'films/edit');
        $jqgrid['url_delete'] = site_url($this->router->directory . 'films/delete');

        $this->smarty->assign('jqgrid', $jqgrid);

        $jqgrid_init = $this->smarty->get_contents('template/backend/js/jqgrid');
        $js_text = array($jqgrid_init);

        $this->smarty->assign('css_files', $css_files);
        $this->smarty->assign('js_files', $js_files);
        $this->smarty->assign('js_text', $js_text);
        $this->smarty->assign('title', $films->localize_label('manager'));

        // view
        $this->smarty->view('backend/news/jqgrid', 'grid');
        $this->smarty->display('template/backend/admin');
    }

    /**
     * Create news
     *
     * @access public
     */
    public function create() {

        //get category list
        $category = new Category_model();
        $category_list = array(0 => '---'.$this->lang->line('cat')." ".$this->lang->line('root').'---');
        $category->get_list_title($category_list, TRUE, 2);
        $films       	=   new Films_model();
        $partner    	=   new Partner_model();
        $language       =   new Language_model();

        $this->smarty->assign('films', $films);
        $this->smarty->assign('category', $category);
        $this->smarty->assign('category_list', $category_list);
        $this->smarty->assign('partner', $partner);
        $this->smarty->assign('language', $language);

        if ($this->input->server('REQUEST_METHOD') === 'GET') {
            $this->smarty->view('backend/films/edit', 'main_content');
            $this->smarty->display('template/backend/admin');
        }
        //save create
        else {
            $this->load->library('form_validation');
            $this->form_validation->set_rules('title', $this->lang->line('title'), 'trim|required|max_length[150]');

            if ($this->form_validation->run() == TRUE) {
                $films = new Films_model();
                $this->_save(site_url('auth/films'), $films);
            } else {
                $this->smarty->view('backend/films/edit', 'main_content');
                $this->smarty->display('template/backend/admin');
            }
        }
    }

    public function edit() {
        $category = new Category_model();
        $partner    	=   new Partner_model();
        $language       =   new Language_model();
        
        $category_list = array(0 => '---'.$this->lang->line('cat')." ".$this->lang->line('root').'---');
        $category->get_list_title($category_list, TRUE, 2);
        
        $this->smarty->assign('category_list', $category_list);
        $this->smarty->assign('partner', $partner);
        $this->smarty->assign('language', $language);
        
        $films = new Films_model();
        if ($this->input->server('REQUEST_METHOD') === 'GET') {
            $parameters = $this->uri->ruri_to_assoc(3);

            if (isset($parameters['id'])) {
                $id = intval($parameters['id']);
            } else {
                $id = 0;
            }
           $films->get_by_id($id);

            //-------------------
            if ($films->exists()) {
                $this->smarty->assign('films', $films);
                $this->smarty->view('backend/films/edit', 'main_content');
                $this->smarty->display('template/backend/admin');
            } else {
                $this->session->set_flashdata('error_message', $this->lang->line('not_found')/* 'Bài viết này không tồn tại xin vui lòng kiểm tra lại.' */);
                redirect(site_url('auth/films'));
            }
        } else {// save update 
            $this->load->library('form_validation');
            $this->form_validation->set_rules('title', $this->lang->line('title'), 'trim|required|max_length[150]');

            $id = $this->input->post('id');
            $films->get_by_id($id);
            if ($this->form_validation->run() == TRUE) {
                $this->_save(site_url('auth/films/'), $films);
            } else {
                $this->smarty->assign('films', $films);
                $this->smarty->view('backend/films/edit', 'main_content');
                $this->smarty->display('template/backend/admin');
            }
        }
    }

    private function _save($uri, $films) {
        // Begin transaction
        $films->trans_begin();

        $this->load->helper('films');
        
        $user = $this->login_manager->get_user();
        $now = date("Y:m:d H:i:s");
        if (!isset($films->id)) {
            //created          
            $films->build_code(alias_name($this->input->post('title')));
            $films->created = $now;
            $films->creator_id = $user->id;   
        } else {
            //edit
            $films->updated = $now;
            $films->editor_id = $user->id;
        }
       
        $films->title = $this->input->post('title');
        $films->code = alias_name($films->title);
        $films->description = $this->input->post('description');
        $films->content = $this->input->post('content');
        $films->feature = $this->input->post('feature');
        $films->image = $this->input->post('image');
        $films->link = $this->input->post('link');
        $films->films_type = $this->input->post('films_type');
        $films->active = $this->input->post('active');
        $films->category_id = $this->input->post('category_id');
        $films->partner_id = $this->input->post('partner_id');
        $films->language_id = $this->input->post('lang_id');
        $films->url_target = $this->input->post('url_target');
        $films->year = $this->input->post('year');
        $films->nation = $this->input->post('nation');
        $films->is_parts = $this->input->post('is_parts');
        $films->server1 = $this->input->post('link1');
        $films->server2 = $this->input->post('link2');
        $films->server3 = $this->input->post('link3');
        $films->big_image = $this->input->post('big_image');
        //get seo's information
        $films->seo_title = $this->input->post('seo_title');
        $films->metadata = $this->input->post('metadata');
        $films->keyword = $this->input->post('keyword');
        $this->active = 1;
        $this->feature = 1;
        $this->hits = 0;
        //print_r($films);exit;
        $films->save();
        
        $exists = $films->exists();
        // Attempt to save user
        // Check status of transaction
        if ($films->trans_status() === FALSE) {
            // Transaction failed, rollback
            $films->trans_rollback();

            // Add error message
            $u->error_message('transaction', 'The transaction failed to save (insert)');
        } else {
            // Transaction successful, commit
            $films->trans_commit();
            // $this->lang->load('model_Films_model','vietnamese');
            if ($exists) {
                $this->session->set_flashdata('message', $films->localize_label('edit_success')/* 'Đã cập nhật dữ liệu thành công.' */);
            } else {
                $this->session->set_flashdata('message', $films->localize_label('create_success')/* 'Đã lưu dữ liệu thành công.' */);
            }
            redirect($uri);
        }
        // Show all errors
        $error = $films->error->string;

        $this->session->set_flashdata('message', $error);
        edirect($uri);
    }

    /**
     * delete function, delete exists object
     *
     * @access public
     * @param id of object in url
     * @return void
     */
    function delete() {

        $url = 'films';

        $parameters = $this->uri->ruri_to_assoc();

        if (isset($parameters['id'])) {
            $id = intval($parameters['id']);
        } else {
            $id = 0;
        }

        if ($id <= 0) {
            $this->session->set_flashdata('error_message', $this->lang->line('not_found'));
            redirect($this->router->directory . $url);
        }

        $films = new Films_model();
        $films->where('id', $id);
        $films->get(1);

        if ($films->id <= 0) {
            $this->session->set_flashdata('error_message', $this->lang->line('not_found'));
            redirect($this->router->directory . $url);
        }

        $result = $films->delete();
        if ($result === TRUE) {
            $this->session->set_flashdata('message', $films->localize_label('delete_success'));
        } else {
            $this->session->set_flashdata('message', $films->localize_label('delete_fail'));
        }
        redirect($this->router->directory . $url);
    }

    /**
     * init function, get para for jquery grid via ajax
     *
     * @access public
     * @param null
     * @return array in json encode
     */
    function jqgrid_jsoninit() {
        if (IS_AJAX) {
            $films = new Films_model();
            $metadata = $films->jqgrid_metadata();
            echo json_encode($metadata);
        }
    }

    /**
     * data function, get data for jquery grid via ajax
     *
     * @access public
     * @param null
     * @return array in json encode
     */
    function jqgrid_jsondata() {
        $cate = new Category_model();
        $user = new User_model();
        if (IS_AJAX) {
            $search = $this->input->post('_search');
            $filters = json_decode($this->input->post('filters'));
            $order = $this->input->post('sidx');
            $order_direct = $this->input->post('sord');
            $page = intval($this->input->post('page'));
            $num_per_page = intval($this->input->post('rows'));

            $relative_search = array(
                'category' => array(
                    'search' => 'id',
                    'include' => array('id', 'title')
                )
            );

            $this->load->helper('jqgrid');

            $films = jqgrid_search(new Films_model(), $search, $filters, $order, $order_direct, $page, $num_per_page, $relative_search);

            $paged = $films->paged;
            $responce = new Stdclass();
            $responce->page = $paged->current_page; //curent page
            $responce->total = $paged->total_pages; //total page
            $responce->records = $paged->total_rows; //total record
            $i = 0;

            foreach ($films as $item) {
                $isLeaf = TRUE;
                $responce->rows[$i]['cell'] = array(
                    // Field
                    $item->id,
                    $item->title,                                      
                    $cate->get_title_category_id($item->category_id),
                    $user->get_fullname_by_creator_or_editor($item->creator_id),
                    $user->get_fullname_by_creator_or_editor($item->editor_id),
                    format($item->created), 
	                $item->get_active(),
	                $item->get_feature(),
                    intval($item->hits),
                    // Format
                    NULL,
                    NULL,
                    $isLeaf,
                    false
                );
                $i++;
            }
            //print_r($responce); exit;
            echo json_encode($responce);
        }
    }

}

